<template>
  <nav class="nav">
    <div class="nav__wrapper">
      <GameRoomHeader class="hidden-xxs-only"></GameRoomHeader>
      <!-- not login -->
      <div class="nav__nologin nav__login-section" v-if="!isLogined">
        <Button @click="handleLogin">Login</Button>
      </div>
      <!-- login -->
      <div class="nav__logined nav__login-section" v-else>
        <Dropdown
          class="nav__login-section__user"
          @on-click="handleClickDropdown"
        >
          <Avatar :src="player.characterUrl" class="">
            {{ player.name }}</Avatar
          >
          <span class="nav__login-section__user__name">{{ player.name }}</span>
          <DropdownMenu slot="list">
            <DropdownItem disabled>个人档案</DropdownItem>
            <DropdownItem name="token">查看密码</DropdownItem>
            <DropdownItem disabled>设置</DropdownItem>
          </DropdownMenu>
        </Dropdown>

        <Button @click="handleLogout">Logout</Button>
      </div>
    </div>
  </nav>
</template>

<script lang="ts">
import { Component, Prop, Vue } from '@/plugins/class-component-hooks'
import { playerModule } from '../store'
import GameRoomHeader from '@/components/GameRoomHeader.vue'
import { gqlErrorHandler } from '../util/errorHandler'

@Component({
  components: {
    GameRoomHeader
  }
})
export default class NavBar extends Vue {
  get player() {
    return playerModule.player
  }

  get isLogined() {
    return this.player.id !== '' && playerModule.authToken !== ''
  }

  handleLogin() {
    // go to login page
    this.$router.push({ name: 'login' })
  }

  handleLogout() {
    playerModule.logout(this.$apollo.getClient()).catch((err: any) => {
      this.$Message.error(err.message)
    })
    this.$router.push({ name: 'login' })
  }

  handleShowToken() {
    this.$router.push({
      name: 'me',
      params: {
        prevPath: this.$router.currentRoute.fullPath
      }
    })
  }
  handleClickDropdown(name: string) {
    if (name === 'token') {
      this.handleShowToken()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
@import '@/styles/general.scss';

.nav {
  margin-bottom: 1.2 rem;

  &__wrapper {
    display: flex;
    justify-content: center;
    align-items: center;

    &::before {
      content: '';
      margin-right: auto;
    }
  }

  &__login-section {
    display: flex;
    justify-content: space-between;
    // left-align
    margin-left: auto;
    padding: 0.5rem 1rem 0.5rem 0;
    & > * + * {
      margin-left: 1.2rem;
    }

    &__user {
      &__name {
        padding-left: 0.6rem;
        color: gray;
      }
    }
  }
}
</style>
